package com.hzgj.bcl.stats;

import com.google.common.collect.Lists;
import lombok.Setter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TimeCounter {
    private final CopyOnWriteArrayList<Long> values;
    private final ReentrantReadWriteLock lock;
    @Setter
    protected Metric metric;

    public TimeCounter() {
        this.values = Lists.newCopyOnWriteArrayList();
        this.lock = new ReentrantReadWriteLock();
    }

    public int count() {
        return values.size();
    }

    public void update(long value, long time) {
        if (value < 0) {
            return;
        }

        lockForRegularUsage();
        try {
            values.add(value);
        } finally {
            unlockForRegularUsage();
        }
    }

    public Snapshot getSnapshot() {
        lockForRegularUsage();
        try {
            return new Snapshot(values);
        } finally {
            unlockForRegularUsage();
        }
    }

    public void clean() {
        lockForRescale();
        try {
            values.clear();
        } finally {
            unlockForRescale();
        }
    }

    protected void unlockForRescale() {
        lock.writeLock().unlock();
    }

    protected void lockForRescale() {
        lock.writeLock().lock();
    }

    protected void lockForRegularUsage() {
        lock.readLock().lock();
    }

    protected void unlockForRegularUsage() {
        lock.readLock().unlock();
    }

    public static final long oneMinute = 60 * 1000; //1分钟

    public static long getNearestTargetByMinuteSpan(long time, long intervalSpan) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        int second = calendar.get(Calendar.SECOND);
        calendar.set(Calendar.MILLISECOND,0);
        long target;
        if (second != 0) {
            calendar.add(Calendar.MINUTE, 1);
            calendar.set(calendar.SECOND, 0);
        }
        target = calendar.getTimeInMillis();
        return target;
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long time = simpleDateFormat.parse("2016-09-12 14:59:02").getTime();
//        long time = 1481868405122l;
        System.out.println(new Date(getNearestTargetByMinuteSpan(time, 1)));
    }
}
